<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        const baseURL = 'http://localhost:3001/?name=';


        window.onload = () => {
            document.querySelector('[type="button"]').addEventListener('click', function (e) {
                let name = this.previousSibling.value;
                exportExcelByXhr(name);
                // exportExcelByFetch(name);
            });
        };


        //Fetch实现文件下载
        function exportExcelByFetch(name = '') {
            fetch(baseURL + name, {
                method: 'GET', // or 'PUT'
                body: null, // data can be `string` or {object}!
                headers: new Headers({
                    'responseType': 'blob'
                })
            })
                .then(response => response.blob())
                .then(data => {
                    handleBlob(data);
                });
        }


        //XMLHttpRequest实现文件下载
        function exportExcelByXhr(name = '') {
            var xhr = new XMLHttpRequest();
            xhr.timeout = 3000;
            xhr.ontimeout = (event) => alert("请求超时！");
            xhr.responseType = 'blob';
            xhr.open('GET', baseURL + name, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                    //下载操作：文件流在xhr.response中
                    // console.log(xhr.response);
                    handleBlob(xhr.response);
                }
            }
            xhr.send(null);//请求数据
        }


        //处理后端返回的Blob
        function handleBlob(responseData) {
            if (responseData.type === "application/json") {
                const reader = new FileReader();
                reader.onload = function () {
                    const { msg } = JSON.parse(reader.result);
                    alert(`后端消息：${msg}`);
                }
                reader.readAsText(responseData, 'utf-8');
            } else {
                // 如果后端响应头中没有指定 MIME Type , 就需要前端转一下
                // const blob = new Blob([responseData], {
                //     type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                // });
                openDownloadFile(responseData, '列表');
            }
        }


        /**
         * 下载文件
         * @param {any} urlObj 要下载的地址 或者 Blob对象
         * @param {any} saveName 文件保存的名字 可选参数
         */
        function openDownloadFile(urlObj, saveName) {
            var openDownload = function (href, fileName) {
                var downloadElement = document.createElement('a');
                downloadElement.target = "_blank";
                downloadElement.href = href;
                downloadElement.download = fileName || ""; // HTML5新增的属性，指定保存文件名，可以不要后缀
                document.body.appendChild(downloadElement);
                downloadElement.click(); // 点击下载
                document.body.removeChild(downloadElement); // 下载完成移除元素
            }

            if (typeof urlObj == 'object' && urlObj instanceof Blob) {
                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    //针对于IE浏览器的处理, 因部分IE浏览器不支持createObjectURL
                    window.navigator.msSaveOrOpenBlob(urlObj, saveName);
                } else {
                    var url = window.URL.createObjectURL(urlObj); // 创建blob地址
                    openDownload(url, saveName);
                    window.URL.revokeObjectURL(url); // 释放掉blob对象创建的地址
                }
            } else {
                openDownload(urlObj, saveName);
            }
        }
    </script>
</head>

<body>
    <input type="text" name="name" placeholder="请输入姓名模糊查询" /><button type="button">导出Excel</button>
</body>

</html>